package performance;

import java.io.File;
import java.io.FileInputStream;
import java.util.Hashtable;

public class Properties extends Hashtable<String, String> {

	/**
	 * 
	 */
	private static final long serialVersionUID = -2191472912493632080L;

	public static Properties read(final File file) {
		return new Properties(file);
	}

	public static Properties read(final String path) {
		return new Properties(path);
	}

	private final File file;

	private String propertyText;

	private Properties(final File file) {
		this.file = file;
		this.checkFile();
		this.init();
		this.parse();
	}

	private Properties(final String name) {
		this(new File(name));
	}

	private void checkFile() {
		if (this.getFile() == null)
			throw new IllegalArgumentException("El archivo no puede ser null");
		if (!this.getFile().exists())
			throw new IllegalArgumentException("El archivo no existe");
		if (!this.getFile().canRead())
			throw new IllegalArgumentException("No se puede leer el archivo");
	}

	private File getFile() {
		return file;
	}

	private String getPropertyText() {
		return propertyText;
	}

	private void init() {
		try {
			final FileInputStream input = new FileInputStream(this.getFile());
			final byte[] buffer = new byte[input.available()];
			input.read(buffer);
			this.setPropertyText(new String(buffer));
		} catch (final Exception e) {
			throw new ProfilerException("error al leer el archivo", e);
		}
	}

	private void parse() {
		final String[] propertyTuples = this.getPropertyText().split("\\\n");
		for (final String propertyTupe : propertyTuples) {
			final String[] property = propertyTupe.split("=");
			this.put(property[0], property[1].trim());
		}

	}

	private void setPropertyText(final String propertyText) {
		this.propertyText = propertyText;
	}

}
